package com.thrd.basicframework.ui.recyclerview;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.AbsListView;
import android.widget.ExpandableListView;

/**
 * 2级列表
 * @author: ${唐杰}
 * @date: 2021/3/24
 */
public class ScrollExpandableListView extends ExpandableListView implements AbsListView.OnScrollListener {
    public ScrollExpandableListView(Context context) {
        this(context,null);
    }

    public ScrollExpandableListView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ScrollExpandableListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setOnScrollListener(this);
        }
    }


    public void scroll(int groupIndex, int childIndex) {
        int position = 0;
        for (int i = 0; i < groupIndex; i++) {
            position++;
            if (isGroupExpanded(i)){
                position = position + getExpandableListAdapter().getChildrenCount(i);
            }
        }
        position++;
        position = position + childIndex-1;
        super.setSelection(position);
    }



    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
// 判断滚动到底部
        //  int position= view.getLastVisiblePosition();
        int position= view.getFirstVisiblePosition();
        if (position !=-1&&onClickScrollStateChanged!=null) {
            for (int i = 0; i < getExpandableListAdapter().getGroupCount(); i++) {
                position= position- getExpandableListAdapter().getChildrenCount(i);
                if(position<=0){
                    onClickScrollStateChanged.onClickScrollPosition(i);
                    return;
                }
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    private OnClickScrollStateChanged onClickScrollStateChanged;
    public interface  OnClickScrollStateChanged{
        void onClickScrollPosition(int position);
    }

    public OnClickScrollStateChanged getOnClickScrollStateChanged() {
        return onClickScrollStateChanged;
    }

    public void setOnClickScrollStateChanged(OnClickScrollStateChanged onClickScrollStateChanged) {
        this.onClickScrollStateChanged = onClickScrollStateChanged;
    }
}
